package tech.jabari.user.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import tech.jabari.base.BaseResponse;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

/**
 * 上传头像。
 * @author Jabari Lu
 * @title: UploadServlet
 * @data 2020/8/14 11:34
 */
@WebServlet("/upload")
@MultipartConfig // 表示支持上传文件的处理。
public class UploadServlet extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取头像文件的part对象
        Part part = req.getPart("headImg");
        // 2.保存图片到服务器
        // 2.1.获取服务器保存图片的目录。
        String realPath = req.getServletContext().getRealPath("/upload");
        // 2.2.获取头像的文件名。
        String fileName = part.getSubmittedFileName();
        String path = realPath + "/" + fileName;
        // 2.3.将头像文件写入到服务器。
        part.write(path);
        String ret = "<h1>--------图片上传成功，<br/>路径：" + path + "</h1>";
        System.out.println(ret);
        resp.getWriter().write(ret);
        /*resp.setContentType("application/json;charset=UTF-8");
        ObjectMapper objectMapper = new ObjectMapper();
        BaseResponse<String> result = new BaseResponse<>(200, "OK", "/upload/" + fileName);
        resp.getWriter().write(objectMapper.writeValueAsString(result));*/
    }
}
